//
//  editNameController.m
//  SoundPill
//
//  Created by 宋鹏鹏 on 15/4/13.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "editNameController.h"
#import "UIViewExt.h"
#import "AFNetworking.h"
#import "JSONKit.h"
#import "LoginViewController.h"
#import "JCAlertView.h"
@interface editNameController ()<UITextFieldDelegate>
{
    UITextField *textfield;
    UIBarButtonItem *sureBtn;
}
@end

@implementation editNameController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改用户名";
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    [sure setFrame:CGRectMake(0, 0, 30, 30)];
    [sure setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    sureBtn = [[UIBarButtonItem alloc] initWithCustomView:sure];
//    sureBtn.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = sureBtn;
    //self.navigationItem.rightBarButtonItem.title = @"确定";
    
    sureBtn.enabled = NO;
    
    //设置导航栏样式
 
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0) {
        
        self.edgesForExtendedLayout=UIRectEdgeNone;
        
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    textfield = [[UITextField alloc]initWithFrame:CGRectMake(self.view.width*0.04, 10, self.view.width*0.92, 44)];
    textfield.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.4 alpha:0.1];
    textfield.textColor = [UIColor blackColor];
    textfield.textAlignment = NSTextAlignmentCenter;
    textfield.placeholder = @"请输入昵称";
    textfield.delegate = self;
    textfield.enablesReturnKeyAutomatically = YES;
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取字典类型NSDictionary类型的数据
    NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
    textfield.text = [myDictionary objectForKey:@"username"];
    
    textfield.borderStyle = UITextBorderStyleRoundedRect;
    textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
    textfield.font = [UIFont systemFontOfSize:16];
    textfield.returnKeyType = UIReturnKeyDone;
    
    [self.view addSubview:textfield];
}

- (void)sureBtnClick
{
    //保存名字
    [self postUserName:textfield.text];
}
#pragma mark------传UserName
- (void)postUserName:(NSString *)name
{
    //
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
     AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];

    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:name forKey:@"username"];
    if (uid!=nil) {
        [dataDic setObject:uid forKey:@"user"];
    }else{
    }
    //NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",self.listdataModel.CinemeID];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [session.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    NSLog(@"%@",dataDic);
    [session POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:name forKey:@"username"];
        myDictionary = dic;
        
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //保存名字（注册成功后）
        [userDefaultes setObject:name forKey:@"username"];
        [userDefaultes synchronize];
        
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        if (statusCode == 422) {
            //提示用户名已被占用
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"此用户名已被使用" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }else  if (statusCode == 401) {
            //在别的地方登录，token过期，需重新登录
            
            // 加载主视图控制器
            LoginViewController *login = [[LoginViewController alloc] init];
            self.view.window.rootViewController = login;
            
        } else {
            //提示断网（网络异常－请重试）
            [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
            //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络异常" message:@"确保在有Wifi或信号良好的地方重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            //            // optional - add more buttons:
            //            [alert show];
        }

    }];
}
//
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self sureBtnClick];
        
    }else if (buttonIndex == 1){
        
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [textfield becomeFirstResponder];
}
//
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [textfield resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    [textfield resignFirstResponder];
    [self sureBtnClick];
    return YES;
}

//
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [textfield addTarget:self action:@selector(textLengthChange:) forControlEvents:UIControlEventEditingChanged];
}
//实现textLengthChange方法
-(void)textLengthChange:(id)sender{
    
    if (textfield.text.length<=0 ) {
        [sureBtn setEnabled:NO];
    }else{
        [sureBtn setEnabled:YES];
    }
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
